<template>
    <div class="captcha-container">
      <el-input class="input-class"  v-model="captchaInput" placeholder="请输入验证码" clearable/>
      <canvas class="canvas-class" ref="captchaCanvas" width="115" height="35" ></canvas>
      <button class="button-class" @click="generateCaptcha">
      </button>
      <p v-if="captchaInput && captchaInput !== captchaCode">验证码错误</p>
    </div>
  </template>
  
  <script>
  export default {
    name: 'CaptchaComponent',  // 改为多单词的组件名称
    data() {
      return {
        captchaCode: '',
        captchaInput: '',
      };
    },
    mounted() {
      this.generateCaptcha();
    },
    methods: {
      generateCaptcha() {
        const canvas = this.$refs.captchaCanvas;
        const ctx = canvas.getContext('2d');
        ctx.fillStyle = this.getRandomColor();
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.font = '30px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        const code = this.generateRandomCode();
        this.captchaCode = code;
        ctx.fillStyle = this.getRandomColor();
        ctx.fillText(code, canvas.width / 2, canvas.height / 2);
        this.drawRandomLines(ctx, canvas.width, canvas.height);
      },
      generateRandomCode() {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let code = '';
        for (let i = 0; i < 4; i++) {
          code += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return code;
      },
      getRandomColor() {
        const r = Math.floor(Math.random() * 256);
        const g = Math.floor(Math.random() * 256);
        const b = Math.floor(Math.random() * 256);
        return `rgb(${r}, ${g}, ${b})`;
      },
      drawRandomLines(ctx, width, height) {
        for (let i = 0; i < 5; i++) {
          ctx.beginPath();
          ctx.moveTo(Math.random() * width, Math.random() * height);
          ctx.lineTo(Math.random() * width, Math.random() * height);
          ctx.strokeStyle = this.getRandomColor();
          ctx.lineWidth = 1;
          ctx.stroke();
        }
      },
    },
  };
  </script>
  
  <style scoped>
  .captcha-container {
    width: 100%;
    text-align: center;
   
  }
  .input-class {
    border-radius: 10px;
    /* margin-top: 20px; */
    
    width: 150px;
    height: 40px;
    color: #eae5e594;
    border-radius: 10px;
   }
   .canvas-class {
    width:"115"; 
    margin-top: 20px;
   }
   .button-class {
    width: 35px;
    height: 35px;
    background-image: url("../pages/img/shuaxin1.png");
    margin-top: 20px;
   }

  canvas {
    border: 1px solid #ccc;
  }
  
  input {
    margin-top: 10px;
  }
  </style>
  